package com.aratana.ui.fields.br;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

import com.aratana.type.br.CNPJ;
import com.aratana.ui.fields.BasicField;

public class CnpjField extends BasicField<CNPJ> {

	private static final long serialVersionUID = 840813759710998567L;

	@SuppressWarnings("serial")
	public CnpjField() {
		setDocument(new PlainDocument() {

			@Override
			public void insertString(final int offs, final String str, final AttributeSet a) throws BadLocationException {
				String original = CnpjField.this.getText().replaceAll("[^0-9]", "");
				if (!original.isEmpty()) {
					original = new Long(original).toString();
				}
				final StringBuilder text = new StringBuilder(allSelected ? "" : original).append(str.replaceAll("[^0-9]", ""));
				super.remove(0, getLength());
				if (text.length() > 14) {
					text.delete(0, text.length() - 14);
				}

				if (text.length() > 0 && Long.parseLong(text.toString()) > 0) {
					super.insertString(0, CNPJ.format(text.toString()), a);
				}
				allSelected = false;
			}

			@Override
			public void remove(final int offs, final int len) throws BadLocationException {
				super.remove(offs, len);
				if (len != getLength()) {
					insertString(0, "", null);
				}
			}
		});

		addFocusListener(new FocusAdapter() {

			@Override
			public void focusLost(final FocusEvent e) {
				if (getText().length() > 0 && !CNPJ.isValid(getText())) {
					setText("");
				}
			}
		});

		addCaretListener(new CaretListener() {

			boolean update = false;

			@Override
			public void caretUpdate(final CaretEvent e) {
				if (!update && e.getDot() == e.getMark() && !allSelected) {
					update = true;
					allSelected = getSelectionStart() != getSelectionEnd() && getSelectionEnd() == getText().length();
					setCaretPosition(getText().length());
					update = false;
				}
			}
		});
		setText("0");
	}

	@Override
	public int getMax() {
		return 18;
	}
}
